_realname=llama.cpp
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=r980.f31b5397
pkgrel=1
pkgdesc="Port of Facebook's LLaMA model in C/C++ (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64')
url="https://github.com/ggerganov/llama.cpp"
license=('spdx:MIT')
depends=(
  "${MINGW_PACKAGE_PREFIX}-openblas"
  "${MINGW_PACKAGE_PREFIX}-gcc-libs"
)
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-cmake"
  "${MINGW_PACKAGE_PREFIX}-ninja"
  "${MINGW_PACKAGE_PREFIX}-cc"
  'git'
)
_commit='f31b5397143009d682db90fd2a6cde83f1ef00eb'
source=("${_realname}"::"git+https://github.com/ggerganov/llama.cpp.git#commit=${_commit}")
sha256sums=('SKIP')

pkgver() {
  cd "${srcdir}/${_realname}"

  printf "r%s.%s" "$(git rev-list --count "${_commit}")" "$(git rev-parse --short "${_commit}")"
}

prepare() {
  cd "${srcdir}/${_realname}"
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    "${MINGW_PREFIX}"/bin/cmake.exe \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      -DLLAMA_BLAS=ON \
      -DLLAMA_BLAS_VENDOR=OpenBLAS \
      ../${_realname}

  "${MINGW_PREFIX}"/bin/cmake.exe --build .
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" "${MINGW_PREFIX}"/bin/cmake.exe --install .

  # Install the examples by prefixing them with llama.cpp
  # except main.exe, which gets installed as plain llama.cpp.exe
  cd "${pkgdir}${MINGW_PREFIX}"
  for i in bin/*.{exe,py}; do
    mv "${i}" "${pkgdir}${MINGW_PREFIX}/bin/${_realname}-${i//bin\//}"
  done
  cd -
  mv "${pkgdir}${MINGW_PREFIX}/bin/${_realname}-main.exe" \
    "${pkgdir}${MINGW_PREFIX}/bin/${_realname}.exe"

  install -Dm644 "${srcdir}/${_realname}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
